<?php
namespace App\Domain\Appfc114;

use App\Common\Util as Util;
use App\Model\Appfc114\Customer as ModelCustomer;
use App\Model\Appfc114\Visit as ModelVisit;
use PhalApi\Exception\BadRequestException;
use Illuminate\Database\Capsule\Manager as DB;

class Customer  {

    protected $query;
    protected $metaData;

    protected $baseCode;
    public $province_code;//省编码
    public $city_code;//城市编码
    public $borough_option;//行政区
    public $toward_option; //房屋朝向
    public $fitment_type_option; //内部装修
    public $facilities_option;//内部配套
    public $require_purpose_option;//购房目的
    public $require_type_option;  //需求类型
    public $house_level_option;//房源等级
    public $origin_option;//客户来源
    public $visit_type_option;//访问类型

    function __construct() {
        $this->query = new QueryCommon();
        $this->metaData = new MetaData();

        $this->baseCode = \PhalApi\DI()->config->get('basecode');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode');//省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode');//城市

        $this->borough_option = $this->metaData->getPairBaseCodeByType($this->city_code);//区域列表
        $this->toward_option   = $this->metaData->getPairBaseCodeByType(215);
        $this->fitment_type_option    = $this->metaData->getPairBaseCodeByType(219);
        $this->require_purpose_option = $this->metaData->getPairBaseCodeByType(10103);//购房目的
        $this->require_type_option = $this->metaData->getPairBaseCodeByType(10102);//需求类型
        $this->house_level_option  = $this->metaData->getPairBaseCodeByType(242);//房源等级
        $this->origin_option = $this->metaData->getPairBaseCodeByType(10105);//客户来源
        $this->visit_type_option = $this->metaData->getPairBaseCodeByType(10106);//访问类型
    }

    /* 客户列表 */
    public function getList($uid){
        $params = \PhalApi\DI()->request->getAll();
        $model = new ModelCustomer();

        $where = [];
        $whereRaw = " a.flag=1";
        $page_info ="";
        $by = trim(isset($params["by"])?$params["by"]:'all');
        $orderField = isset($params['sort'])?$params['sort'] : " a.create_date";
        $orderValue = isset($params['sort_value']) ? $params['sort_value'] : ' desc,a.rating asc';
        $page = isset($params["page"])?$params["page"]:1;
        $limit = isset($params["pageSize"])?$params["pageSize"]:30;

        $filter = array();//筛选条件
        $filter['by'] = $by;
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $page_info .="sort=".$orderField."&sort_value=".$orderValue."&by=".$by."&page=".$page."&";

        $keywords = isset($param['keywords'])?$param['keywords']:'';
        if($keywords!=''){
            $whereRaw .= " and (a.name like '%".$keywords."%' or a.mobile like '".$keywords."%')";
            $page_info .="keywords=".$keywords."&";
            $filter['keywords'] = $keywords;
        }else{
            $filter['keywords'] = $keywords;
        }

        $limitdata = $this->query->getPaginationDC($page,$limit);
        $items = $model->getListItems($where,$whereRaw, $limitdata, $orderField.$orderValue);
        foreach ($items as $key => $value) {
            $item[$key] = $this->tranCustomerInfo($value);
        }
        return $items;
    }

    /* 添加客户 */
    public function add($user_id){
        $params = \PhalApi\DI()->request->getAll();
        $data = $this->query->FilterField("crm_customer",$params);
        $data["owner_uid"] = $user_id;
        $data["create_uid"] = $user_id;
        $data["create_date"] = time();
        $data["write_uid"] = $user_id;
        $data["write_date"] = time();
        $cinfo =$this->getTeltoInfo($data["mobile"],$user_id);

        if(isset($cinfo["id"])){
            return $cinfo["id"];
            throw new BadRequestException('您已添加了相同的手机号客户,不能重复添加!', 1);
            exit;
        }

        $model = new ModelCustomer();
        return $model->insertGetId($data);
    }

    /* 更新客户 */
    public function update($params,$user_id) {
        $model = new ModelCustomer();
        $data = $this->query->FilterField("crm_customer",$params);
        $id = $params["customer_id"];
        $data["write_date"] = time();
        $data["write_uid"] = $user_id;

        return $model->where("id",$id)->where("owner_uid",$user_id)->update($data);
    }

    /* 客户详情 */
    public function detail($customer_id,$user_id){
        $model = new ModelCustomer();
        return $model->where("id",$customer_id)->where("owner_uid",$user_id)->first();
    }

    /* 根据电话获取客户信息 */
    public function getCustomerInfoByMobile($mobile,$user_id){
        $model = new ModelCustomer();
        return $model->where("mobile",$mobile)->where("owner_uid",$user_id)->first();
    }

    /* 添加客户并添加到访 */
    public function addCustomerAndVisit($user_id){
        $params = \PhalApi\DI()->request->getAll();
        $data = $this->query->FilterField("crm_customer",$params);
        $data["owner_uid"] = $user_id;
        $data["create_uid"] = $user_id;
        $data["create_date"] = time();
        $data["write_uid"] = $user_id;
        $data["write_date"] = time();
        $customerInfo =$this->getCustomerInfoByMobile($data["mobile"],$user_id);

        if(isset($customerInfo["id"])){
            //判断该客户是否已经报备该项目
            $visitInfo = $this->getVisitInfo($customerInfo['id'],$params['require_project_id'],$user_id);
            if(isset($visitInfo["id"])){
                //return $customerInfo["id"];
                throw new BadRequestException('该客户已报备,不能重复报备!', 1);
                exit;
            }
            $vdata = $this->query->FilterField("crm_visit",$params);
            $vdata["customer_id"] = $customerInfo['id'];
            $vdata["action_id"] = $params['require_project_id'];
            $vdata["owner_uid"] = $user_id;
            $vdata["create_uid"] = $user_id;
            $vdata["create_date"] = time();
            $model = new ModelVisit();
            //添加到访
            $model->insertGetId($vdata);
            return $customerInfo["id"];
        }else{
            $modelCustomer = new ModelCustomer();
            //处理价格
            $price = explode('-',$params['require_price']);
            $data['require_min_price'] = $price[0];
            $data['require_max_price'] = $price[1];
            //处理面积
            $area = explode('-',$params['require_area']);
            $data['require_min_area'] = $area[0];
            $data['require_max_area'] = $area[1];

            //添加客户
            $modelCustomer->setTable('crm_customer');
            $customerId = $modelCustomer->insertGetId($data);

            $vdata = $this->query->FilterField("crm_visit",$params);
            $vdata["customer_id"] = $customerId;
            $vdata["action_id"] = $params['require_project_id'];
            $vdata["owner_uid"] = $user_id;
            $vdata["create_uid"] = $user_id;
            $vdata["create_date"] = time();
            $modelVisit = new ModelVisit();
            //添加到访
            $modelVisit->insertGetId($vdata);

            return $customerId;
        }
    }

    /* 添加到访 */
    public function addVisit($user_id)
    {
        $params = \PhalApi\DI()->request->getAll();
        $data = $this->query->FilterField("crm_visit",$params);
        $data["owner_uid"] = $user_id;
        $data["create_uid"] = $user_id;
        $data["create_date"] = time();
        $model = new ModelVisit();
        return $model->insertGetId($data);
    }

    /* 到访列表 */
    public function getVisitlist($uid){
        $model = new ModelVisit();
        $where = [];
        $where["crm_visit.owner_uid"]=$uid;
        $params = \PhalApi\DI()->request->getAll();
        $whereRaw = " crm_visit.flag=1 ";

        if(isset($params['keywords'])  && !empty($params['keywords']))//关键字查询
            $whereRaw.= " and (crm_customer.name like '%{$params['keywords']}%' or crm_customer.mobile = '{$params['keywords']}')";
        if(isset($params['visit_type'])  && !empty($params['visit_type']))
            $where["visit_type"] = $params['visit_type'];

        $orderField = isset($params['sort'])?$params['sort'] : 'create_date';
        $orderValue = isset($params['sort_value'])?$params['sort_value'] : ' desc';
        $page = isset($params["page"])?$params["page"]:1;
        $limit = isset($params["pageSize"])?$params["pageSize"]:30;
        $limitData = $this->query->getPaginationDC($page,$limit);
        DB::connection()->enableQueryLog();
        $items = $model
            ->leftJoin("crm_customer","crm_visit.customer_id","=","crm_customer.id")
            ->leftJoin("fc_project","crm_visit.action_id","=","fc_project.id")
            ->where($where)
            ->whereRaw($whereRaw)
            ->orderBy($orderField,$orderValue)
            ->skip($limitData["offset"])
            ->take($limitData["limit"])
            ->get(["crm_visit.*","crm_customer.name as cname","crm_customer.mobile as mobile","crm_customer.sex as sex","crm_customer.require_max_price","crm_customer.require_min_price","crm_customer.require_max_area","crm_customer.require_min_area","crm_customer.require_shi","fc_project.name as pname"]);

        foreach ($items as $key => $value) {
            $items[$key]["visit_date_val"] = isset($value["visit_date"])?date("m-d H:i",$value["visit_date"]):"";
            $items[$key]["create_date_val"] = date("Y-m-d",$value["create_date"]);

            $visitTypeInfo = $this->transVisitType($value['visit_type']);
            $items[$key]["visit_type_val"] = $visitTypeInfo['visit_type_val'];
            $items[$key]["visit_type_color"] = $visitTypeInfo['visit_type_color'];
        }
        return $items;
    }

    /* 到访详情 */
    public function detailVisit($id,$user_id){
        //DB::connection()->enableQueryLog();
        $model = new ModelVisit();
        $data = $model
            ->leftJoin("crm_customer","crm_visit.customer_id","=","crm_customer.id")
            ->where("crm_visit.id",$id)
            ->where("crm_visit.owner_uid",$user_id)
            ->first(["crm_visit.*","crm_customer.status","crm_customer.name as cname","crm_customer.mobile as mobile","crm_customer.sex as sex","crm_customer.require_max_price","crm_customer.require_min_price","crm_customer.require_max_area","crm_customer.require_min_area","crm_customer.require_shi"]);
        //print_r(DB::getQueryLog());exit;
        $data["visit_date_val"] = isset($data["visit_date"])?date("Y-m-d H:i",$data["visit_date"]):"";
        $data["create_date_val"] = date("Y-m-d H:i",$data["create_date"]);
        $visitTypeInfo = $this->transVisitType($data['visit_type']);
        $data["visit_type_val"] = $visitTypeInfo['visit_type_val'];
        $data["visit_type_color"] = $visitTypeInfo['visit_type_color'];
        $data['status_val'] = $this->baseCode['customer_status_option'][$data['status']];
        $data['mobile_src'] = str_replace('0000','****',$data['mobile']);

        return $data;
    }

    /* 获取到访信息 */
    public function getVisitInfo($customer_id,$project_id,$user_id){
        $model = new ModelVisit();
        return $model->where("customer_id",$customer_id)->where("owner_uid",$user_id)->where("action_id",$project_id)->first();
    }

    /* 删除到访 */
    public function deleteVisit($visit_id){
        $model = new ModelVisit();
        return $model->destroy($visit_id);
    }

    /* 将客户信息转换为详细信息 */
    public function tranCustomerInfo($Info){
        $Info['price_uitl'] = ($Info['require_type']==1010201)?"元/月":"万元";
        $Info['project_title'] = ($Info['require_pm_type']==20306)?"楼盘":"小区"; //todo 此处什么意思呢
        //根据物业类型处理相关数据
        switch ($Info['require_pm_type']){
            case '20306':
                $this->facilities_option      = $this->metaData->getPairBaseCodeByType(232);
                break;
            default:
                $this->facilities_option      = $this->metaData->getPairBaseCodeByType(217);
                break;
        }
        $Info['require_borough'] = explode(",", $Info['require_borough']);
        $Info['require_borough_val'] = $this->tranMateData($Info['require_borough'],$this->borough_option);
        $Info['require_purpose'] = explode(",", $Info['require_purpose']);
        $Info['require_purpose_val'] = $this->tranMateData($Info['require_purpose'],$this->require_purpose_option);
        $Info['require_facilities'] = explode(",", $Info['require_facilities']);
        $Info['require_facilities_val'] = $this->tranMateData($Info['require_facilities'],$this->facilities_option);
        $Info['require_fitment_type_val'] = $this->fitment_type_option[$Info['require_fitment_type']];
        $Info['require_type_val'] = $this->require_type_option[$Info['require_type']];
        $Info['status_val'] = $this->baseCode->customer_status_option[$Info['status']];
        $Info['scr_mobile'] = substr($Info['mobile'], 0, 3) . "*******";
        $Info['require_shi'] = explode(",", $Info['require_shi']);

        //性别处理
        if($Info['sex']==1){
            $Info['avtor'] = '-m2';
            $Info['msmr'] = '先生';
        }else{
            $Info['avtor'] = '-w3';
            $Info['msmr'] = '女士';
        }

        //客户等级
        $Info['rating_val'] = $this->config->rating_option [$Info['rating']];

        //创建时间
        $Info['create_date_long']=date('Y-m-d H:i:s', $Info['create_date']);
        $Info['create_date_short']=date('Y-m-d', $Info['create_date']);

        //获取录入人员名称
        $user = $this->query->getRow("select user_name,true_name,is_admin from sys_user where id='{$Info['create_uid']}' and flag=1");
        $Info['create_name'] = $user['true_name'];

        //负责人员名称
        $user = $this->query->getRow("select a.user_name,a.true_name,a.is_admin,b.org_name from sys_user as a left join sys_orgstruct as b on a.department_id=b.id where a.id='{$Info['owner_uid']}' and a.flag=1");
        $Info['owner_name'] = $user['true_name'];
        $Info['org_name'] = $user['org_name'];

        //物业
        $Info['require_pm_type_val'] = $this->baseCode->pm_type_option[$Info['require_pm_type']];

        //获取商圈
        $business_region = explode(',',$Info['require_business_region']);
        if(count($business_region)>0) {
            foreach ($business_region as $code){
                $Info['business_region'] .= $this->metaData->getNameByCode($code).'、';
            }
            $Info['business_region'] = Util::msubstr($Info['business_region'],0,-1);
        }
        //获取小区
        $project_ids = explode(',',$Info['require_project_id']);
        if(count($project_ids)>0) {
            //$this->loadModel('fc_project');
            foreach ($project_ids as $code){
                //$Info['project_name'] .= $this->fc_project->getNameById($code).'、';
            }
            //$Info['project_name'] = Util::msubstr($Info['project_name'],0,-1);
        }

        //统计带看
        $sql = "select count(*) as cnt from crm_visit where flag=1 and customer_id={$Info['id']}";
        $visit_cnt = $this->query->getRow($sql);
        $Info['visit_cnt'] =  $visit_cnt['cnt'];

        //统计跟进日志
        $sql = "select count(*) as cnt from crm_r_customer_log where customer_id={$Info['id']}";
        $log_cnt = $this->query->getRow($sql);
        $Info['log_cnt'] =  $log_cnt['cnt'];

        //最后一次跟进
        $sql = "select a.id,a.log_id,a.customer_id,b.create_date from crm_r_customer_log as a LEFT JOIN crm_log as b on a.log_id=b.id where a.customer_id={$Info['id']} and b.flag=1 order by a.id desc limit 0,1";
        $log = $this->query->getRow($sql);
        if(isset($log['create_date'])) {
            $Info['out_time'] = time()-$log['create_date'];
            //$Info['log_create_date'] = Util::formatDate($log['create_date']).'跟进';
            $Info['log_create_date_val'] = date('Y-m-d H:i', $log['create_date']);
        }else{
            $Info['out_time'] = time()-$Info['create_date'];
            $Info['log_create_date'] = '没有跟进信息';
            $Info['log_create_date_val'] = $Info['log_create_date'];
        }
        return $Info;
    }

    /* 转换到访类型 */
    private function transVisitType($visit_type){
        $info = '';
        switch ($visit_type){
            case '1010601':
                $info['visit_type_val'] = '报备';
                $info['visit_type_color'] = 'bg-orange';
                break;
            case '1010602':
                $info['visit_type_val'] = '到访';
                $info['visit_type_color'] = 'bg-blue';
                break;
            default:
                $info['visit_type_val'] = '报备';
                $info['visit_type_color'] = 'bg-orange';
                break;
        }
        return $info;
    }

    /* 转换简直为中文 */
    private function tranMateData($ids,$mateData){
        $purpose = '';
        foreach ($ids as $id){
            $purpose .= $mateData[$id].'、';
        }
        $purpose = Util::msubstr($purpose,0,-1);
        return $purpose;
    }
}
